<template lang="html">
  <div v-loading="loading" class="main-panel">
    <el-button type="primary" @click="bannerDialog('post')">添加</el-button>
    <el-table
      :data="bannerTableData"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="event"
        label="事件"
      />
      <el-table-column
        prop="event_id"
        label="事件ID"
      >
        <template slot-scope="scope">
          {{ identifyEvent(scope.row.event, scope.row.event_id) }}
        </template>
      </el-table-column>
      <el-table-column
        label="图片"
      >
        <template slot-scope="scope">
          <el-image
            style="width: 50%"
            :src="scope.row.media_url"></el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="create_time"
        label="创建时间"
      />
      <el-table-column
        label="是否是轮播图"
      >
        <template slot-scope="scope">
          {{ scope.row.is_carousel === true ? '是' : '不是' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="update_time"
        label="更新时间"
      />
      <el-table-column
        fixed="right"
        label="操作"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="bannerDialog('put',scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteBanner(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align:center;margin-top:20px">
      <el-pagination
        :current-page="bannerTableDataPaginateCurrentPage"
        :page-sizes="bannerTableDataPaginateTotalPageSizes"
        :page-size="bannerTableDataPaginateTotalPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="bannerTableDataPaginateTotal"
        @size-change="bannerTableDataHandleSizeChange"
        @current-change="bannerTableDataHandleCurrentChange"
      >
        <!-- <span>当前{{ bannerTableDataPaginateCurrentPage }}页，</span>
                        <span>共{{ bannerTableDataPaginateLastPage }}页</span> -->
      </el-pagination>
    </div>
    <el-dialog title="编辑" :visible.sync="bannerDiaIsShow" class="diaForm" :append-to-body="false">
      <el-form
        ref="bannerRef"
        :model="bannerForm"
        :rules="bannerRules"
        label-width="140px"
      >
        <el-form-item label="事件" prop="event">
          <el-col :span="15">
            <el-radio v-model="bannerForm.event" label="category" @change="changeEven">跳转到商品分类</el-radio>
            <el-radio v-model="bannerForm.event" label="product" @change="changeEven">跳转到商品</el-radio>
            <el-radio v-model="bannerForm.event" label="article" @change="changeEven">跳转到文章</el-radio>
          </el-col>
        </el-form-item>
        <el-form-item label="事件ID" prop="event_id">
          <el-col :span="15">
            <el-select
              v-model="bannerForm.event_id"
              filterable
              remote
              clearable
              reserve-keyword
              placeholder="请选择事件ID"
              :remote-method="getEventIdRemote"
              :loading="loading"
            >
              <el-option
                v-for="item in eventIdOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="是否是轮播图" prop="is_carousel">
          <el-col :span="15">
            <el-switch
              v-model="bannerForm.is_carousel"
              active-text="是"
              inactive-text="否"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-col>
        </el-form-item>
        <el-form-item label="图片" prop="media_ids">
          <el-col :span="6">
            <el-upload
              class="avatar-uploader"
              :action="uploadMediaAction"
              :show-file-list="false"
              :headers="{'authorization': token}"
              :on-success="handleMediaSuccess">
              <img v-if="media_url !== null" :src="media_url" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="editBanner()"
          >确认
          </el-button>
          <el-button @click="bannerDiaIsShow = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getToken
} from '@/utils/auth'

export default {
  components: {},
  data() {
    return {
      loading: false,
      bannerSearchForm: {},
      bannerTableData: [],
      bannerTableDataPaginateCurrentPage: 1,
      bannerTableDataPaginateTotal: 1,
      bannerTableDataPaginateLastPage: 1,
      bannerTableDataPaginateTotalPageSize: 10,
      bannerTableDataPaginateTotalPageSizes: [10, 20, 50, 100],
      bannerTab: [],
      bannerEditType: 'post',
      bannerDiaIsShow: false,
      bannerForm: {
        is_carousel: true
      },
      bannerRules: {
        event: [{
          required: true,
          trigger: 'blur'
        }],
        event_id: [{
          required: true,
          trigger: 'blur'
        }],
        is_carousel: [{
          required: true,
          trigger: 'blur'
        }],
        media_url: [{
          required: true,
          trigger: 'blur'
        }]
      },
      eventIdOptions: [],
      eventIdTableData: [],
      productSearchForm: {},
      productTableData: [],
      categorySearchForm: {},
      categoryTableData: [],
      articleSearchForm: {},
      articleTableData: [],
      media_url: null
    }
  },
  computed: {
    token: function() {
      return getToken()
    },
    uploadMediaAction: function() {
      return process.env.VUE_APP_BASE_API + '/media/upload/file'
    }
  },
  created() {
    this.getProductList(1, 10000)
    this.getCategoryList(1, 10000)
    this.getArticleList(1, 10000)
    this.getBannerList()
  },
  methods: {
    changeEven(v) {
      this.$nextTick(() => {
        this.$set(this.bannerForm, 'event_id', null)
      })
      switch (v) {
        case 'product':
          this.eventIdOptions = this.productTableData
          break
        case 'category':
          this.eventIdOptions = this.categoryTableData
          break
        case 'article':
          this.eventIdOptions = this.articleTableData
          break
        default:
      }
    },
    handleMediaSuccess(res, file) {
      console.log(res)
      // this.logo_url = URL.createObjectURL(file.raw)
      this.media_url = res.data.url
    },
    identifyEvent(v, id) {
      switch (v) {
        case 'product':
          for (let i = 0; i < this.productTableData.length; i++) {
            if (this.productTableData[i].id === id) {
              return v + ' - ' + this.productTableData[i].name
            }
          }
          return id
        case 'category':
          for (let i = 0; i < this.categoryTableData.length; i++) {
            if (this.categoryTableData[i].id === id) {
              return v + ' - ' + this.categoryTableData[i].name
            }
          }
          return id
        case 'article':
          for (let i = 0; i < this.articleTableData.length; i++) {
            if (this.articleTableData[i].id === id) {
              return v + ' - ' + this.articleTableData[i].name
            }
          }
          return id
        default:
          return id
      }
    },
    getEventIdRemote(query) {
      if (query !== '') {
        this.eventIdOptions = this.eventIdTableData.filter(item => {
          return item.label.toLowerCase()
            .indexOf(query.toLowerCase()) > -1
        })
      } else {
        this.eventIdOptions = this.eventIdTableData
      }
    },
    bannerTableDataHandleSizeChange(val) {
      // 改变每页显示的条数
      this.bannerTableDataPaginateTotalPageSize = val
      this.getBannerList(1, this.bannerTableDataPaginateTotalPageSize)
    },
    bannerTableDataHandleCurrentChange(val) {
      this.bannerTableDataPaginateCurrentPage = val
      this.getBannerList(val, this.bannerTableDataPaginateTotalPageSize)
    },
    getBannerList(page = 1, limit = 10) {
      this.loading = true
      this.bannerSearchForm.page = page
      this.bannerSearchForm.limit = limit
      this.$store.dispatch('banner/getBannerList', this.bannerSearchForm).then((res) => {
        this.bannerTableData = res.data.data
        this.bannerTableDataPaginateTotal = res.data.total
        this.bannerTableDataPaginateCurrentPage = res.data.current_page
        this.bannerTableDataPaginateLastPage = res.data.last_page
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    deleteBanner(row) {
      // console.log(row)
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          this.$store.dispatch('banner/deleteBanner', { id: row.id }).then((res) => {
            this.getBannerList()
            this.loading = false
            this.bannerDiaIsShow = false
            this.$message({
              type: 'success',
              message: res.msg
            })
          }).catch(() => {
            this.loading = false
            return false
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    editBanner() {
      switch (this.bannerEditType) {
        case 'post':
          console.log(this.bannerForm)
          this.$refs['bannerRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              this.bannerForm.media_url = this.media_url
              this.$store.dispatch('banner/postBanner', this.bannerForm).then((res) => {
                this.getBannerList()
                this.bannerForm = {}
                this.loading = false
                this.bannerDiaIsShow = false
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
        case 'put':
          this.$refs['bannerRef'].validate((valid) => {
            if (valid) {
              this.loading = true
              this.bannerForm.media_url = this.media_url
              this.$store.dispatch('banner/putBanner', this.bannerForm).then((res) => {
                this.getBannerList()
                this.bannerForm = {}
                this.loading = false
                this.bannerDiaIsShow = false
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }).catch(() => {
                this.loading = false
              })
            } else {
              return false
            }
          })
          break
      }
    },
    bannerDialog(type, row) {
      this.bannerDiaIsShow = true
      switch (type) {
        case 'post':
          this.bannerEditType = 'post'
          this.media_url = row.media_url
          break
        case 'put':
          this.bannerEditType = 'put'
          // 这里一定要使用nextTick的方式赋值，不然会卡住input
          this.changeEven(row.event)
          this.media_url = row.media_url
          this.$nextTick(() => {
            this.$set(this.bannerForm, 'id', row.id)
            this.$set(this.bannerForm, 'event', row.event)
            this.$set(this.bannerForm, 'event_id', row.event_id)
            this.$set(this.bannerForm, 'is_carousel', row.is_carousel)
          })
          break
        default:
      }
    },
    getProductList(page = 1, limit = 10) {
      this.loading = true
      this.productSearchForm.page = page
      this.productSearchForm.limit = limit
      this.$store.dispatch('product/getProductList', this.productSearchForm).then((res) => {
        this.productTableData = res.data.data
        this.productTableDataPaginateTotal = res.data.total
        this.productTableDataPaginateCurrentPage = res.data.current_page
        this.productTableDataPaginateLastPage = res.data.last_page
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getCategoryList(page = 1, limit = 10) {
      this.loading = true
      this.categorySearchForm.page = page
      this.categorySearchForm.limit = limit
      this.$store.dispatch('product/getCategoryList', this.categorySearchForm).then((res) => {
        this.categoryTableData = res.data.data
        this.categoryTableDataPaginateTotal = res.data.total
        this.categoryTableDataPaginateCurrentPage = res.data.current_page
        this.categoryTableDataPaginateLastPage = res.data.last_page
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    getArticleList(page = 1, limit = 10) {
      this.loading = true
      this.articleSearchForm.page = page
      this.articleSearchForm.limit = limit
      this.$store.dispatch('article/getArticleList', this.articleSearchForm).then((res) => {
        this.articleTableData = res.data.data
        this.articleTableDataPaginateTotal = res.data.total
        this.articleTableDataPaginateCurrentPage = res.data.current_page
        this.articleTableDataPaginateLastPage = res.data.last_page
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.main-panel {
  padding: 18px;
  font-size: 10px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
